<!--
	* @author  gaohailan
  * @desc 先模创新工作室-先模创新工作室简介新增、编辑
-->
<template>
  <div id="laborModelEdit">
    <div class="btn-container-title">
      <span>新建/编辑</span>
    </div>
    <el-form
      v-show="type == 2"
      ref="projectForm"
      :model="projectForm"
      :rules="projectRules"
      class="dataForm"
      label-position="right"
      label-width="140px"
      style="width: 80%;margin: 0 auto"
    >
      <el-form-item label="成果名称" prop="name" required>
        <el-input v-model="projectForm.name" style="width: 50%" />
      </el-form-item>
      <el-form-item label="分类" prop="classifyId" required>
        <el-select v-model="projectForm.classifyId" style="width: 50%">
          <el-option v-for="(item,index) in classifyList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="封面图片" required>
        <image-upload
          :key="uploadFile.imagecropperKey"
          v-model="projectForm.img"
          :preview-id="uploadFile.viewId"
          :forever="true"
          :width="702"
          :view="uploadFile.view"
          :height="310"
          :no-circle="true"
          :no-rotate="false"
          lang-type="zh"
        />
      </el-form-item>
      <el-form-item label="详情图片" required>
        <image-upload
          :key="uploadFile.imagecropperInfoKey"
          v-model="projectForm.infoImg"
          :preview-id="uploadFile.viewId2"
          :forever="true"
          :width="702"
          :view="uploadFile.view"
          :height="310"
          :no-circle="true"
          :no-rotate="false"
          lang-type="zh"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input v-model="projectForm.leader" style="width: 50%" maxlength="10"/>
      </el-form-item>
      <!-- 团队成员 -->
      <el-form-item label="团队成员">
        <div style="display:flex;align-items:left">
          <div style="width:60%">
            <div v-for="(item,index) in items" :key="index">
              <el-input v-model="item.title" style="width: 83%;margin: 0 10px 10px 0" />
              <el-button icon="el-icon-delete" round size="mini" type="primary" @click="delItem(item,index)" />
            </div>
          </div>
          <el-button round size="mini" style="height:28px;margin-top:5px" type="primary" @click="addItem">新增
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="企业名称" prop="orgName">
        <el-input v-model="projectForm.orgName" style="width: 50%" />
      </el-form-item>
      <el-form-item label="项目简介" prop="info" required>
        <tinymce v-if="showtinymce" v-model="projectForm.info" :height="300" />
      </el-form-item>

      <el-form-item label="创新成果" prop="resultText">
        <tinymce v-if="showtinymce" v-model="projectForm.resultText" :height="300" />
      </el-form-item>
      <el-form-item label="获奖情况" prop="award">
        <tinymce v-if="showtinymce" v-model="projectForm.award" :height="300" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="projectForm.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="状态" prop="state" required>
        <el-select v-model="projectForm.state" placeholder="请选择">
          <el-option key="0" :value="0" label="禁用" />
          <el-option key="1" :value="1" label="启用" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="common-btns">
      <el-button style="padding: 8px 30px;" @click="cancel">取消</el-button>
      <el-button style="padding: 8px 30px;" type="primary" @click=" state =='create'?createData():updateData()">确定
      </el-button>
    </div>
  </div>
</template>

<!--suppress SpellCheckingInspection -->
<script>
import { number, specialText } from '@/utils/validate'
import {
  className,
  insert,
  get,
  update,
  del
} from '../api'
import Tinymce from '@/components/Tinymce'
import ImageUpload from '@/components/ImageUpload'
import ImageUploads from '@/components/ImageUploads'
export default {
  name: 'LaborModelEdit',
  components: { Tinymce, ImageUpload, ImageUploads },
  data() {
    return {
      state: 'create',
      curActivety: '新闻',
      type: 1,
      id: '',
      projectForm: {
        name: '', // 创新项目名称
        classifyId: '', // 分类ID
        img: '',
        infoImg: '',
        infoUrl: [],
        leader: '', // 负责人
        personName: '', // 团队成员
        orgName: '', // 企业名称
        info: '', // 简介
        resultText: '', // 创新成果
        award: '', // 获奖情况
        sort: '',
        state: 1 // 状态 0禁用 1启用
      },
      classifyList: [], // 成果分类
      attachment: [],
      projectRules: {
        name: [
          { required: true, message: '请输入成果名称', trigger: 'blur' },
          { validator: specialText, message: '成果名称格式有误', trigger: 'blur' }
        ],
        classifyId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        orgName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        info: [
          { required: true, message: '请输入项目简介', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        leader: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        sort: [{ validator: number, message: '请输入正确排序', trigger: 'blur' }]
        // type: [
        //   { required: true, message: '请选择正文类型', trigger: 'change' }
        // ],
      },
      roomInfoUrlArr: [],
      roomScore: false,
      isWatch: true,
      items: [{ 'title': '' }],
      itemsRoom: [{ 'title': '' }],
      showtinymce: true,
      uploadFile: {
        viewId: '',
        viewId2: '',
        limit: 5,
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        imagecropperInfoKey: 0,
        showUpload: false,
        accept: '',
        fileType: '',
        fileIndex: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false  // 是否为OSS存储，如果是的直接返回文件全路径，不需要拼接接口地址
      }
    }
  },
  created() {
    this.id = this.$route.query.id || ''
    this.type = this.$route.query.type || ''
    this.getClassifyList()
    if (this.id) {
      this.showtinymce = false
      this.isWatch = false
      this.getinnovateInfo(this.id)
      this.state = 'update'
    }
  },
  methods: {
    createData() {
      this.$refs['projectForm'].validate((valid) => {
        if (valid) {
          const postData = this.projectForm
          // postData.img = this.projectForm.img.slice(0,-4)
          postData.img = this.projectForm.img
          postData.infoUrl = JSON.stringify([{ 'fileName': 'blob', 'id': this.projectForm.infoImg, 'type': '' }])
          if (this.projectForm.infoUrl == '') {
            this.$message({
              message: '请上传详情图片',
              type: 'warning'
            })
            return
          }
          const personName = []
          this.items.forEach((item) => {
            personName.push(item.title)
          })
          postData.personName = personName.join(',')
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          return new Promise((resolve, reject) => {
            insert(postData).then(() => {
              loading.close()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1500
              })
              this.$router.push({ path: '/innovationStudio/innovationResult' })
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['projectForm'].validate((valid) => {
        if (valid) {
          const postData = this.projectForm
          postData.img = this.projectForm.img
          postData.infoUrl = JSON.stringify([{ 'fileName': 'blob', 'id': this.projectForm.infoImg || this.projectForm.infoUrl, 'type': '' }])
          if (this.projectForm.infoUrl == '') {
            this.$message({
              message: '请上传详情图片',
              type: 'warning'
            })
            return
          }
          const personName = []
          this.items.forEach((item) => {
            personName.push(item.title)
          })
          postData.personName = personName.join(',')
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          return new Promise((resolve, reject) => {
            update(postData).then(() => {
              loading.close()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1500
              })
              this.$router.push({ path: '/innovationStudio/innovationResult' })
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },
    cancel() {
      this.$router.push({ path: '/innovationStudio/innovationResult' })
    },
    getinnovateInfo(id) {
      return new Promise((resolve, reject) => {
        get({id: id}).then(response => {
          this.projectForm = response.data.data
          this.$nextTick(() => {
            this.showtinymce = true
          })
          this.projectForm.infoUrl = JSON.parse(response.data.data.infoUrl)[0].id
          this.uploadFile.viewId = this.projectForm.img
          this.uploadFile.viewId2 = this.projectForm.infoUrl
          const personArr = response.data.data.personName ? response.data.data.personName.split(',') : []
          this.items = []
          personArr.forEach((item) => {
            this.items.push({ 'title': item })
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    addItem() {
      this.items.push({ 'title': '' })
    },
    delItem(items, index) {
      if (this.items.length === 1) {
        this.$message.error('最少显示一条')
        return
      }
      this.items.splice(index, 1)
    },
    addItemRoom() {
      this.itemsRoom.push({ 'title': '' })
    },
    delItemRoom(items, index) {
      if (this.itemsRoom.length === 1) {
        this.$message.error('最少显示一条')
        return
      }
      this.itemsRoom.splice(index, 1)
    },
    /* 分类信息获取*/
    getClassifyList() {
      var query = {
        parentId: '-1' // 父级ID
      }
      return new Promise((resolve, reject) => {
        className().then(response => {
          this.classifyList = response.data.data
        }).catch(error => {
          reject(error)
        })
      })
    },
    getRoomScore(value) {
      if (value === '0') {
        this.roomScore = true
      } else {
        this.roomScore = false
      }
    }
  }
}
</script>

<style lang="scss">
$mainColor: #18A5FD;
.custom-uploader{
  //position: absolute;
}
.el-select .el-input {
  width: 150px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

#laborModelEdit {
  background-color: #fff;
  padding: 40px;
  min-height: calc(100vh - 84px);

  .btn-container-title {
    flex: 1;
    height: 36px;
    line-height: 36px;
    font-size: 16px;
    color: rgba(51, 51, 51, 1);
    font-weight: bold;
  }

  .select-data {
    display: inline-block;
    background: rgba(246, 246, 246, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    padding: 0 10px;
    margin-right: 5px;

    i {
      cursor: pointer;
      padding-left: 5px;
    }
  }

  .selectbtn {
    display: inline-block;
    width: 120px;
    background: rgba(255, 255, 255, 1);
    border: 1px dotted $mainColor;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: $mainColor;
    text-align: center;
    cursor: pointer;
  }

  .common-btns {
    text-align: center;
  }

  .start-content {
    height: 100%;

    .el-rate__icon {
      font-size: 26px;
    }
  }
}
</style>
